package jxau.jwgl.service;

import jxau.jwgl.api.EvaluationApi;
import jxau.jwgl.api.MessageData;
import jxau.jwgl.api.WebApiFactory;
import jxau.jwgl.commons.entity.Evaluation;
import jxau.jwgl.task.RunnableCallableTask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * EvaluationTask 后台评教任务
 *
 * @author LongShu 2017/06/11
 */
public class EvaluationTask implements RunnableCallableTask<Object> {
    private static Logger logger = LoggerFactory.getLogger(EvaluationTask.class);

    private static final String IDS = "1,2,3,4,5,6,7,8,9,10";
    private static EvaluationApi evaluatingApi = WebApiFactory.get(EvaluationApi.class);

    private String id;
    private String guid;
    private Evaluation ea;

    private String[] jxbbhs;
    private String[] jsbhs;
    private int count;

    public EvaluationTask(String guid, Evaluation ea) {
        this.id = "Evaluation" + ea.getUsername() + ea.getSemester();
        this.guid = guid;
        this.ea = ea;

        init();
    }

    private void init() {
        jxbbhs = ea.getJxbbh().split(",");
        jsbhs = ea.getJsbh().split(",");

        count = jxbbhs.length > jsbhs.length ? jxbbhs.length : jsbhs.length;

        String ids = ea.getIds();
        if (!StringUtils.endsWith(ids, ",")) {
            ids = IDS;
            ea.setIds(ids);
        }

        String fens = ea.getFens();
        if (fens.length() == 1) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < 10; i++) {
                builder.append(fens).append(",");
            }
            fens = builder.toString();
            ea.setFens(fens);
        }
    }

    /**
     * 要评教的老师数量
     */
    public int getCount() {
        return count;
    }

    /**
     * 学号+学期 作为id
     */
    @Override
    public String getId() {
        return id;
    }

    /**
     * 提交评教
     */
    private Object submit() {
        logger.debug("submit: {}", count);
        long start = System.currentTimeMillis();
        try {
            for (int i = 0; i < count; i++) {
                TimeUnit.MILLISECONDS.sleep(50);// 不休眠可能会出现超时等情况,理想环境下每次评教要6秒左右
                Call<MessageData<Object>> call = evaluatingApi.submitEvaluation(guid, ea.getIds(), ea.getFens(), ea.getPingyu(), jsbhs[i], jxbbhs[i]);
                Response<MessageData<Object>> response = call.execute();
                MessageData<Object> messageData = response.body();
                logger.debug("messageData:{}", messageData);
            }
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            // help gc
            jxbbhs = null;
            jsbhs = null;
            if (logger.isDebugEnabled()) {
                logger.debug("use: {} ms", (System.currentTimeMillis() - start));
            }
        }
        return null;
    }

    @Override
    public void run() {
        submit();
    }

    @Override
    public Object call() {
        return submit();
    }
}
